import { View, Text, Image, Button, Input, Textarea, Picker } from '@tarojs/components'
import { useAuth } from '../../contexts/AuthContext'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { ui } from '../../utils/platform'
import dayjs from 'dayjs'
import './index.less'
import defaultAvatar from '../../assets/images/default-avatar.png'
import { updatePassword, getUserDetail, updateUserDetail } from '../../services/api'

export default function UserProfile({ visible, onClose }) {
  const { userInfo, fetchUserInfo, updatePhoto, updateIntroduce, isLoading } = useAuth()
  
  // 调试日志
  console.log('UserProfile组件 - userInfo:', userInfo);
  console.log('UserProfile组件 - loginType:', userInfo?.loginType);
  
  // 添加状态用于编辑模式
  const [isEditingIntroduce, setIsEditingIntroduce] = useState(false)
  const [isEditingPhoto, setIsEditingPhoto] = useState(false)
  const [introduce, setIntroduce] = useState('')
  const [photoPath, setPhotoPath] = useState('')
  const [photoUrl, setPhotoUrl] = useState('')
  const [saveLoading, setSaveLoading] = useState(false)
  
  // 添加修改密码相关状态
  const [showPasswordModal, setShowPasswordModal] = useState(false)
  const [oldPassword, setOldPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [passwordLoading, setPasswordLoading] = useState(false)
  
  // 添加详细信息页面相关状态
  const [showDetailModal, setShowDetailModal] = useState(false)
  const [detailInfo, setDetailInfo] = useState({})
  const [detailLoading, setDetailLoading] = useState(false)
  const [detailSaveLoading, setDetailSaveLoading] = useState(false)
  const [editingField, setEditingField] = useState(null)
  const [tempValue, setTempValue] = useState('')
  const [selectedDate, setSelectedDate] = useState('')
  // 添加用户昵称状态
  const [userNickName, setUserNickName] = useState('')

  
  const formatDate = (timestamp) => {
    if (!timestamp) return '未获取'
    const date = new Date(timestamp)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  // 根据生日计算年龄
  const calculateAge = (birthday) => {
    if (!birthday) return null
    const birthDate = dayjs(birthday)
    const today = dayjs()
    let age = today.year() - birthDate.year()
    const monthDiff = today.month() - birthDate.month()
    if (monthDiff < 0 || (monthDiff === 0 && today.date() < birthDate.date())) {
      age--
    }
    return age
  }

  // 在组件挂载时和visible变为true时获取用户详细信息
  useEffect(() => {
    if (visible) {
      // 只在抽屉显示时获取用户信息
      fetchUserInfo()
      // 获取用户详细信息中的昵称
      fetchUserNickName()
      // 重置编辑状态
      setIsEditingIntroduce(false)
      setIsEditingPhoto(false)
    }
  }, [visible])
  
  // 当userInfo更新时，同步到编辑表单
  useEffect(() => {
    if (userInfo) {
      setIntroduce(userInfo.introduce || '')
      setPhotoUrl(userInfo.photo || '')
    }
  }, [userInfo])

  // 获取用户昵称的方法
  const fetchUserNickName = async () => {
    try {
      const result = await getUserDetail()
      if (result.code === 100200 && result.data) {
        setUserNickName(result.data.nickName || '')
      }
    } catch (error) {
      console.error('获取用户昵称失败:', error)
    }
  }

  // 进入简介编辑模式
  const handleEditIntroduce = () => {
    setIsEditingIntroduce(true)
  }
  
  // 进入头像编辑模式
  const handleEditPhoto = () => {
    setIsEditingPhoto(true)
    handleChooseImage()
  }
  
  // 取消简介编辑
  const handleCancelIntroduce = () => {
    setIsEditingIntroduce(false)
    // 重置简介为当前用户信息
    if (userInfo) {
      setIntroduce(userInfo.introduce || '')
    }
  }
  
  // 取消头像编辑
  const handleCancelPhoto = () => {
    setIsEditingPhoto(false)
    // 重置头像为当前用户信息
    if (userInfo) {
      setPhotoPath('')
      setPhotoUrl(userInfo.photo || '')
    }
  }
  
  // 选择图片
  const handleChooseImage = async () => {
    try {
      const res = await ui.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })
      
      const tempFilePath = res.tempFilePaths[0]
      setPhotoPath(tempFilePath)
      setPhotoUrl(tempFilePath)
    } catch (error) {
      console.error('选择图片失败:', error)
      ui.showToast({
        title: '选择图片失败',
        icon: 'none',
        duration: 2000
      })
    }
  }
  
  // 保存简介
  const handleSaveIntroduce = async () => {
    setSaveLoading(true)
    try {
      // 确保introduce参数不为null或undefined
      const safeIntroduce = introduce || ''
      
      const result = await updateIntroduce(safeIntroduce)
      
      if (result.success) {
        ui.showToast({
          title: '简介保存成功',
          icon: 'success',
          duration: 2000
        })
        setIsEditingIntroduce(false)
        // 更新成功后刷新用户信息
        fetchUserInfo()
      } else {
        ui.showToast({
          title: result.message || '简介保存失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('保存简介失败:', error)
      Taro.showToast({
        title: error.message || '简介保存失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      setSaveLoading(false)
    }
  }
  
  // 保存头像
  const handleSavePhoto = async () => {
    if (!photoPath) {
      Taro.showToast({
        title: '请选择头像',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    setSaveLoading(true)
    try {
      const result = await updatePhoto(photoPath)
      
      if (result.success) {
        Taro.showToast({
          title: '头像保存成功',
          icon: 'success',
          duration: 2000
        })
        setIsEditingPhoto(false)
        // 清除临时头像路径
        setPhotoPath('')
        // 更新成功后刷新用户信息
        fetchUserInfo()
      } else {
        Taro.showToast({
          title: result.message || '头像保存失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('保存头像失败:', error)
      Taro.showToast({
        title: error.message || '头像保存失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      setSaveLoading(false)
    }
  }

  // 打开修改密码弹窗
  const handleShowPasswordModal = () => {
    setShowPasswordModal(true)
    // 清空密码输入
    setOldPassword('')
    setNewPassword('')
    setConfirmPassword('')
  }

  // 关闭修改密码弹窗
  const handleClosePasswordModal = () => {
    setShowPasswordModal(false)
  }

  // 提交修改密码
  const handleUpdatePassword = async () => {
    // 表单验证
    if (!oldPassword) {
      ui.showToast({ title: '请输入原密码', icon: 'none' })
      return
    }
    if (!newPassword) {
      ui.showToast({ title: '请输入新密码', icon: 'none' })
      return
    }
    if (newPassword !== confirmPassword) {
      ui.showToast({ title: '两次密码输入不一致', icon: 'none' })
      return
    }
    
    setPasswordLoading(true)
    try {
      const result = await updatePassword(oldPassword, newPassword)
      if (result.code === 100200) {
        // 使用API返回的data字段作为提示信息
        ui.showToast({ title: result.data || '密码修改成功', icon: 'success' })
        setShowPasswordModal(false)
      } else {
        ui.showToast({ title: result.msg || '密码修改失败', icon: 'none' })
      }
    } catch (error) {
      console.error('修改密码失败:', error)
      ui.showToast({ title: error.message || '修改失败', icon: 'none' })
    } finally {
      setPasswordLoading(false)
    }
  }

  // 打开详细信息页面
  const handleShowDetailModal = async () => {
    setShowDetailModal(true)
    setDetailLoading(true)
    try {
      const result = await getUserDetail()
      if (result.code === 100200) {
        setDetailInfo(result.data || {})
      } else {
        ui.showToast({ title: result.msg || '获取详细信息失败', icon: 'none' })
      }
    } catch (error) {
      console.error('获取详细信息失败:', error)
      ui.showToast({ title: error.message || '获取失败', icon: 'none' })
    } finally {
      setDetailLoading(false)
    }
  }

  // 关闭详细信息页面
  const handleCloseDetailModal = () => {
    setShowDetailModal(false)
    setEditingField(null)
    setTempValue('')
  }

  // 开始编辑字段
  const handleEditField = (field, currentValue) => {
    setEditingField(field)
    setTempValue(currentValue || '')
    
    // 如果是日期字段，设置日期值
    if (field === 'birthday' && currentValue) {
      setSelectedDate(currentValue)
    } else if (field === 'birthday') {
      setSelectedDate(dayjs().format('YYYY-MM-DD'))
    }
  }

  // 点击字段盒子进入编辑
  const handleFieldClick = (field) => {
    if (editingField !== field) {
      handleEditField(field, detailInfo[field])
    }
  }

  // 取消编辑
  const handleCancelEdit = () => {
    setEditingField(null)
    setTempValue('')
    setSelectedDate('')
  }

  // 保存单个字段
  const handleSaveField = async () => {
    if (!editingField) return
    
    setDetailSaveLoading(true)
    try {
      // 处理日期字段的值
      let fieldValue = tempValue
      if (editingField === 'birthday' && selectedDate) {
        fieldValue = selectedDate
      }
      
      // 构建完整的用户详细信息数据，包含所有字段
      const updateData = {
        nickName: detailInfo.nickName || null,
        medicalHistory: detailInfo.medicalHistory || null,
        sex: detailInfo.sex || null,
        birthday: detailInfo.birthday || null,
        age: detailInfo.age || null,
        zodiac: detailInfo.zodiac || null,
        personalityType: detailInfo.personalityType || null,
        hobbies: detailInfo.hobbies || null,
        country: detailInfo.country || null,
        province: detailInfo.province || null,
        city: detailInfo.city || null,
        // 更新当前编辑的字段
        [editingField]: fieldValue
      }
      
      // 如果更新的是生日字段，自动计算并更新年龄
      if (editingField === 'birthday') {
        const calculatedAge = calculateAge(fieldValue)
        if (calculatedAge !== null) {
          updateData.age = calculatedAge
        }
      }
      
      const result = await updateUserDetail(updateData)
      
      if (result.code === 100200) {
        ui.showToast({ title: result.data || '修改成功', icon: 'success' })
        // 更新本地状态
        setDetailInfo(prev => ({ ...prev, [editingField]: fieldValue }))
        // 如果修改的是昵称，更新昵称状态
        if (editingField === 'nickName') {
          setUserNickName(fieldValue || '')
        }
        setEditingField(null)
        setTempValue('')
        setSelectedDate('')
      } else {
        ui.showToast({ title: result.msg || '修改失败', icon: 'none' })
      }
    } catch (error) {
      console.error('保存字段失败:', error)
      ui.showToast({ title: error.message || '保存失败', icon: 'none' })
    } finally {
      setDetailSaveLoading(false)
    }
  }

  // 字段配置
  const fieldConfig = {
    nickName: { label: '昵称', type: 'input', placeholder: '请输入昵称' },
    medicalHistory: { label: '过往病史', type: 'textarea', placeholder: '请输入过往病史' },
    sex: { label: '性别', type: 'select', options: [{ value: 1, label: '男' }, { value: 0, label: '女' }] },
    birthday: { label: '生日', type: 'date', placeholder: '请选择生日' },
    // age: { label: '年龄', type: 'readonly' }, // 年龄改为只读，自动计算
    zodiac: { 
      label: '星座', 
      type: 'select', 
      options: [
        { value: '白羊座', label: '白羊座' },
        { value: '金牛座', label: '金牛座' },
        { value: '双子座', label: '双子座' },
        { value: '巨蟹座', label: '巨蟹座' },
        { value: '狮子座', label: '狮子座' },
        { value: '处女座', label: '处女座' },
        { value: '天秤座', label: '天秤座' },
        { value: '天蝎座', label: '天蝎座' },
        { value: '射手座', label: '射手座' },
        { value: '摩羯座', label: '摩羯座' },
        { value: '水瓶座', label: '水瓶座' },
        { value: '双鱼座', label: '双鱼座' }
      ]
    },
    personalityType: { 
      label: '性格类型', 
      type: 'select', 
      options: [
        { value: 'INTJ', label: 'INTJ - 建筑师' },
        { value: 'INTP', label: 'INTP - 思想家' },
        { value: 'ENTJ', label: 'ENTJ - 指挥官' },
        { value: 'ENTP', label: 'ENTP - 辩论家' },
        { value: 'INFJ', label: 'INFJ - 提倡者' },
        { value: 'INFP', label: 'INFP - 调停者' },
        { value: 'ENFJ', label: 'ENFJ - 主人公' },
        { value: 'ENFP', label: 'ENFP - 竞选者' },
        { value: 'ISTJ', label: 'ISTJ - 物流师' },
        { value: 'ISFJ', label: 'ISFJ - 守护者' },
        { value: 'ESTJ', label: 'ESTJ - 总经理' },
        { value: 'ESFJ', label: 'ESFJ - 执政官' },
        { value: 'ISTP', label: 'ISTP - 鉴赏家' },
        { value: 'ISFP', label: 'ISFP - 探险家' },
        { value: 'ESTP', label: 'ESTP - 企业家' },
        { value: 'ESFP', label: 'ESFP - 娱乐家' }
      ]
    },
    hobbies: { label: '兴趣爱好', type: 'textarea', placeholder: '请输入兴趣爱好' },
    country: { label: '国家', type: 'input', placeholder: '请输入国家' },
    province: { label: '省份', type: 'input', placeholder: '请输入省份' },
    city: { label: '城市', type: 'input', placeholder: '请输入城市' }
  }

  // 获取显示值的函数
  const getDisplayValue = (field, value) => {
    // 年龄字段特殊处理，自动计算
    if (field === 'age') {
      const calculatedAge = calculateAge(detailInfo.birthday)
      return calculatedAge !== null ? `${calculatedAge}岁` : '未设置'
    }
    
    const config = fieldConfig[field]
    if (config && config.type === 'select' && config.options) {
      const option = config.options.find(opt => opt.value == value)
      return option ? option.label : '未设置'
    }
    return value || '未设置'
  }

  return (
    <View className={`userprofile-drawer ${visible ? 'visible' : ''}`}>
      <View className='userprofile-content'>
        <View className='close-button' onClick={onClose}>
          <Text className='close-icon'>×</Text>
        </View>
        
        <View className='profile-header'>
          <View className='profile-avatar' onClick={handleEditPhoto}>
            <Image 
              className='avatar-image' 
              src={photoUrl || userInfo?.photo || defaultAvatar} 
            />
            {isEditingPhoto && <View className='avatar-edit-overlay'>点击更换头像</View>}
          </View>
          <Text className='profile-name'>{userNickName || userInfo?.name || '未设置昵称'}</Text>
          
          {!isEditingIntroduce && !isEditingPhoto ? (
            <View className='profile-actions'>
              <Button className='edit-button' onClick={handleEditIntroduce}>编辑简介</Button>
              {userInfo?.loginType !== 'wechat' && (
                <Button className='password-button' onClick={handleShowPasswordModal}>修改密码</Button>
              )}
              <Button className='detail-button' onClick={handleShowDetailModal}>详细信息</Button>
            </View>
          ) : isEditingIntroduce ? (
            <View className='edit-actions'>
              <Button className='cancel-button' onClick={handleCancelIntroduce}>取消</Button>
              <Button className='save-button' loading={saveLoading} onClick={handleSaveIntroduce}>保存简介</Button>
            </View>
          ) : isEditingPhoto ? (
            <View className='edit-actions'>
              <Button className='cancel-button' onClick={handleCancelPhoto}>取消</Button>
              <Button className='save-button' loading={saveLoading} onClick={handleSavePhoto}>保存头像</Button>
            </View>
          ) : null}
        </View>
        
        <View className='profile-info'>
          {isLoading ? (
            <View className='loading-info'>加载用户信息中...</View>
          ) : (
            <>
              <View className='info-item'>
                <Text className='item-label'>注册时间：</Text>
                <Text className='item-value'>{formatDate(userInfo?.time)}</Text>
              </View>
              <View className='info-item'>
                <Text className='item-label'>个人简介：</Text>
                {isEditingIntroduce ? (
                  <Textarea
                    className='item-textarea'
                    value={introduce}
                    onInput={e => setIntroduce(e.detail.value)}
                    placeholder='请输入个人简介'
                    maxlength={200}
                  />
                ) : (
                  <Text className='item-value'>{userInfo?.introduce || '未设置'}</Text>
                )}
              </View>
            </>
          )}
        </View>
      </View>
      
      {/* 修改密码弹窗 */}
      {showPasswordModal && (
        <View className='password-modal'>
          <View className='modal-content'>
            <Text className='modal-title'>修改密码</Text>
            
            <View className='modal-form'>
              <View className='form-item'>
                <Text className='item-label'>原密码：</Text>
                <Input
                  className='item-input'
                  type='password'
                  placeholder='请输入原密码'
                  value={oldPassword}
                  onInput={e => setOldPassword(e.detail.value)}
                />
              </View>
              
              <View className='form-item'>
                <Text className='item-label'>新密码：</Text>
                <Input
                  className='item-input'
                  type='password'
                  placeholder='请输入新密码'
                  value={newPassword}
                  onInput={e => setNewPassword(e.detail.value)}
                />
              </View>
              
              <View className='form-item'>
                <Text className='item-label'>确认密码：</Text>
                <Input
                  className='item-input'
                  type='password'
                  placeholder='请再次输入新密码'
                  value={confirmPassword}
                  onInput={e => setConfirmPassword(e.detail.value)}
                />
              </View>
            </View>
            
            <View className='modal-actions'>
              <Button className='cancel-button' onClick={handleClosePasswordModal}>取消</Button>
              <Button className='confirm-button' loading={passwordLoading} onClick={handleUpdatePassword}>确认修改</Button>
            </View>
          </View>
          <View className='modal-overlay' onClick={handleClosePasswordModal}></View>
        </View>
      )}
      
      {/* 详细信息抽屉 */}
      {showDetailModal && (
        <View className='detail-drawer'>
          <View className='detail-content'>
            <View className='detail-header'>
              <Text className='detail-title'>详细信息</Text>
              <View className='detail-close' onClick={handleCloseDetailModal}>
                <Text className='close-icon'>×</Text>
              </View>
            </View>
            
            <View className='detail-body'>
              {detailLoading ? (
                <View className='loading-info'>加载详细信息中...</View>
              ) : (
                <View className='detail-list'>
                  {Object.entries(fieldConfig)
                    .filter(([field]) => field !== 'age') // 排除年龄字段
                    .map(([field, config]) => (
                    <View 
                      key={field} 
                      className='detail-list-item'
                      onClick={() => handleFieldClick(field)}
                    >
                      <View className='item-content'>
                        <Text className='item-label'>{config.label}</Text>
                        <View className='item-right'>
                          <Text className='item-value'>
                            {getDisplayValue(field, detailInfo[field]) || '未设置'}
                          </Text>
                          <Text className='arrow-icon'>›</Text>
                        </View>
                      </View>
                    </View>
                  ))}
                  
                  {/* 年龄字段单独显示，不可编辑 */}
                  <View className='detail-list-item'>
                    <View className='item-content'>
                      <Text className='item-label'>年龄</Text>
                      <View className='item-right'>
                        <Text className='item-value'>
                          {getDisplayValue('age', detailInfo.age) || '未设置'}
                        </Text>
                      </View>
                    </View>
                  </View>
                </View>
              )}
            </View>
          </View>
        </View>
      )}
      
      {/* 编辑字段页面 */}
      {editingField && (
        <View className='edit-drawer'>
          <View className='edit-content'>
            <View className='edit-header'>
              <View className='edit-back' onClick={handleCancelEdit}>
                <Text className='back-icon'>‹</Text>
              </View>
              <Text className='edit-title'>设置{fieldConfig[editingField]?.label}</Text>
              <Button 
                className='edit-done-button' 
                loading={detailSaveLoading} 
                onClick={handleSaveField}
              >
                完成
              </Button>
            </View>
            
            <View className='edit-body'>
              <View className='edit-form'>
                {fieldConfig[editingField]?.type === 'textarea' ? (
                  <Textarea
                    className='edit-textarea'
                    value={tempValue}
                    onInput={e => setTempValue(e.detail.value)}
                    placeholder={fieldConfig[editingField]?.placeholder}
                    maxlength={200}
                    autoFocus
                  />
                ) : fieldConfig[editingField]?.type === 'select' ? (
                  <View className='edit-select-list'>
                    {fieldConfig[editingField]?.options.map(option => (
                      <View 
                        key={option.value} 
                        className={`edit-select-item ${tempValue == option.value ? 'selected' : ''}`}
                        onClick={() => setTempValue(option.value)}
                      >
                        <Text className='select-label'>{option.label}</Text>
                        {tempValue == option.value && (
                          <Text className='check-icon'>✓</Text>
                        )}
                      </View>
                    ))}
                  </View>
                ) : fieldConfig[editingField]?.type === 'date' ? (
                  <View className='edit-date-picker'>
                    <Picker
                      mode='date'
                      value={selectedDate || dayjs().format('YYYY-MM-DD')}
                      start='1900-01-01'
                      end={dayjs().format('YYYY-MM-DD')}
                      fields='day'
                      onChange={(e) => {
                        const date = e.detail.value
                        setSelectedDate(date)
                        setTempValue(date)
                      }}
                    >
                      <View className='selected-date-display'>
                        <Text className='date-display-text'>
                          {selectedDate ? dayjs(selectedDate).format('YYYY年MM月DD日') : '请选择生日'}
                        </Text>
                        <Text className='picker-arrow'>›</Text>
                      </View>
                    </Picker>
                  </View>
                ) : (
                  <Input
                    className='edit-input'
                    type='text'
                    value={tempValue}
                    onInput={e => setTempValue(e.detail.value)}
                    placeholder={fieldConfig[editingField]?.placeholder}
                    autoFocus
                  />
                )}
              </View>
            </View>
          </View>
          <View className='edit-overlay' onClick={handleCancelEdit}></View>
        </View>
      )}
            

    </View>
  )
}
